package com.xinxin.websocket.utils;

import com.xinxin.websocket.dao.UserRepository;
import com.xinxin.websocket.dataobject.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author ：史鑫鑫
 * @date ：Created in 2019/4/29 12:51
 */

@Component
public class WebSocketUtils {
    //  这里使用静态，让 service 属于类
    @Autowired
    private UserRepository userRepository;

    private static WebSocketUtils webSocketUtils;

    @PostConstruct
    public void init() {
        webSocketUtils = this;
        webSocketUtils.userRepository = this.userRepository;
    }

    /**
     * 在线用户
     */
    public static final Map<String, Session> USERS_ONLINE = new ConcurrentHashMap<>();

    /**
     * 向所有用户发送消息
     * @param message
     */
    public static void sendMessageToAllOnlineUser(String message) {
        USERS_ONLINE.forEach((username, session) -> sendMessage(session, message));
    }

    /**
     * 向指定用户发送消息
     * @param session 用户session
     * @param message 消息内容
     */
    private static void sendMessage(Session session, String message) {
        if (session == null) {
            return;
        }
        final RemoteEndpoint.Basic basic = session.getBasicRemote();
        if (basic == null) {
            return;
        }
        try {
            basic.sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取全部在线用户
     * @return
     */
    public static List<User> getAllOnlineUser() {
        return webSocketUtils.userRepository.findByNameIn(USERS_ONLINE.keySet());
    }

    public static void updateUser(String name, String msg){
        User user = webSocketUtils.userRepository.findByName(name);
        user.setMessage(msg);
        webSocketUtils.userRepository.save(user);
    }
}
